# Create your views here.
from user import * 
from glue.forum import *
from search import *
from django.db.models import Q
from django.shortcuts import redirect
from django.http import Http404

# NOTICE: This is the top level module, do not import this file.

def ShortCut(request,name):
    service_t = loader.get_template('core/shortcut.html')
    try:
      data = ServiceCore.objects.get(name=name)
      c = Context({'REQUEST':request.REQUEST,'DATA':data})
      return HttpResponse(service_t.render(c),mimetype = "text/xml")
    except ServiceCore.DoesNotExist:
      return HttpResponse("Error")

def Admin(request):
# The get service will always provides all the services
    services = ServiceCore.objects.all()
    data_t = loader.get_template('core/list.html')
    c = Context({'DATA':services,'SESSION':request.session})
    response = HttpResponse(data_t.render(c),mimetype = "text/html")
    response['Cache-Control'] = 'no-cache'
    return response

# added by mike
@browser_prefix
def DefaultList(request):
    #"x":-33.889221191,"y":151.125427246}
    filter_str = '{"LOCATION":{"x":-26,"y":141},"TARGET":"general","MAIN":"","STYPE":"All",\
    "LOCAL":"","NATION":"Asia,Australia,Europe,China,Korea,Japan,Viet Nam,Thailand,Malaysia,Singapore,Philippines,America,Africa","RADIUS":3000,\
    "PRICE":{"MIN":0,"MAX":9876},"AGE":"","OAD":""}'
    return commList(request,filter_str)

# added by mike for city list
@browser_prefix
def CityList(request,cityName):
  filter_str = ''
  if (cityName == 'sydney'):
    filter_str = '{"LOCATION":{"x":-33.86899948120117,"y":151.2091827392578},"TARGET":"general","MAIN":"","STYPE":"All", \
    "LOCAL":"","NATION":"Australia,China,Hong Kong,India,Japan,Korea,Lebanon,Macau,Malaysia,Mongolia,Russian,Singapore,South Africa,Taiwan,Thailand,Turkey,Viet Nam","RADIUS":1000,\
    "PRICE":{"MIN":0,"MAX":900},"AGE":"","OAD":"Sydney CBD, New South Wales"}'
  else:
    return redirect('/home')

  return commList(request,filter_str)

#changed by mike 
@browser_prefix
def List(request):

    filter_str = request.REQUEST['filter']
    
    return commList(request,filter_str);

def commList(request,filter_str):
    filter_dict = json.loads(filter_str)
    items = Info.objects
    service_name_list = []
    distances = {}
    loc = None

    if(filter_dict.has_key('RADIUS')):
      search_radius = filter_dict['RADIUS']
      if (search_radius==3000 or search_radius==1000):
        search_radius=6
    if(filter_dict.has_key('PRICE')):
      min_price = filter_dict['PRICE']['MIN']
    if(filter_dict.has_key('AGE')):
      girl_age = filter_dict['AGE']
    if(filter_dict.has_key('NATION')):
      search_nation = filter_dict['NATION']
    if(filter_dict.has_key('STYPE')):
      search_type = filter_dict['STYPE']
    if (filter_dict['TARGET'] == 'general'):
      services = GetServices(filter_dict);
      if(filter_dict.has_key('LOCATION')):
        loc = filter_dict['LOCATION']
      #for srv in services:
      #  service_name_list.append(srv.name)
      #items = items.filter(path="item",service__in=service_name_list)
      #context = {'DATA':services,'SIDEDATA':items,"LOC":loc,"DIS":distances, 'CSS_ROOT':'default'}
      
      # ------------------------------------------------------------
      # changed by mike for display the original search condiction
      # context = {'TARGET':'general' ,'DATA':services, "LOC":loc,"DIS":distances, 'CSS_ROOT':'default'}
      # search_radius = filter_dict['RADIUS']
      # min_price = filter_dict['PRICE']['MIN']
      # girl_age = filter_dict['AGE']
      context = {'TARGET':'general' ,'DATA':services, "LOC":loc,"DIS":distances, 'CSS_ROOT':'default', "SRadius":search_radius,"MinPrice":min_price,"GirlAge":girl_age,"SNATION":search_nation,"LSTYPE":search_type}
      # context = {'TARGET':'general' ,'DATA':services, "LOC":loc,"DIS":distances, 'CSS_ROOT':'default'}
            
      isIphone = (lambda x:'iPhone' in x or False)(request.META['HTTP_USER_AGENT'])
      if(isIphone):
        data_t = loader.get_template('mobile/iphone_list.html')
      else:
        data_t = loader.get_template('core/list.html')

      # data_t = loader.get_template('mobile/iphone_list.html')
      c = RequestContext(request,context)
      response = HttpResponse(data_t.render(c),mimetype = "text/html")
      response['Cache-Control'] = 'no-cache'
      return response
    elif (filter_dict['TARGET'] == 'item'):
      girl_age = filter_dict['AGE']
      services = GetServices(filter_dict);
      if(filter_dict.has_key('LOCATION')):
        loc = filter_dict['LOCATION']
      for srv in services:
        service_name_list.append(srv.name)
      path = "item"
      items = items.filter(path = "item",service__in=service_name_list)
      dsp_reg = ""
      # filter nationality
      if(filter_dict.has_key('NATION')):
        nationstr = filter_dict['NATION']
        key = "nationality"
        dsp_reg = BuildDataQueryReg(nationstr,key)
        if(dsp_reg):
          query = Q(data__regex = dsp_reg)
          items = items.filter(query)
      # filter age
      if(filter_dict.has_key('AGE')):
        agestr = filter_dict['AGE']
        key = "age"
        dsp_reg = BuildDataQueryReg(agestr,key)
        if(dsp_reg):
          query = Q(data__regex = dsp_reg)
          items = items.filter(query)
      
      if(dsp_reg == ""):
        context = {'TARGET':'item' ,'SIDEDATA' : items, "LOC":loc,"DIS":distances, 'CSS_ROOT':'default',"SRadius":search_radius,"GirlAge":girl_age,"SNATION":search_nation,"LSTYPE":search_type}
      else:
        context = {'TARGET':'item' ,'SIDEDATA' : items, 'REGEXP':dsp_reg, "LOC":loc,"DIS":distances, 'CSS_ROOT':'default',"SRadius":search_radius,"GirlAge":girl_age,"SNATION":search_nation,"LSTYPE":search_type}
      
      data_t = loader.get_template('core/list.html')
      c = RequestContext(request,context)
      response = HttpResponse(data_t.render(c),mimetype = "text/html")
      response['Cache-Control'] = 'no-cache'
      return response
    else:
      return HttpResponse("Sorry, Invalidate Target " + filter_dict['TARGET'])
    return HttpResponse("Sorry, No Main Search Str Found")

@browser_prefix
def ServiceBySData(request,name,sdata):
  return ServiceFun(request,name)

@browser_prefix
def Service(request,name):
  return ServiceFun(request,name)

def ServiceFun(request,name):
    aut = HasAuthority(request,name)
    service_t = None
    today = date.today()
    now = datetime.now()
    tstamp = now.strftime("%Y-%m-%d-%H-%M-%S")
    dic = {}
    try:
      data = ServiceCore.objects.get(name=name)
      if (aut['r'] == True):
        dic['HAS_AUTHORITY'] = True
        dic['TIME_STAMP'] = tstamp
      gnode = etree.parse(CONFIG.SERVICES_PATH + name+'/config.xml')
      layout = Layout.InitLayoutConfig(gnode.getroot())
      gallery = Gallery.InitGalleryConfig(gnode.getroot())
      forum_info = XMLForum.InitForumConfig(layout.RightNode())
      gallery_info = gallery.BasicInfo()
      layout_info = layout.GetLayout()
      photo_info = PhotoPlay.InitPhotoPlayConfig(gnode.getroot()).BasicInfo()
      template = layout.GetTemplate()
      color = layout.GetColor()
      dic['CSS_ROOT'] = template 
      dic['CSS_COLOR'] = color 
      comp_dict = {'news':'comp/contrib/_news.html',
                 'icon':'comp/contrib/_icon.html',
                 'gallery':'comp/contrib/_gallery.html',
                 'item':'comp/contrib/_items.html',
                 'photoplayer':'comp/contrib/_photoplayer.html',
                 'timetable':'comp/contrib/_timetable.html',
                 'rates':'comp/contrib/_rates.html'}
      if (request.REQUEST.has_key('comp') and comp_dict.has_key(request.REQUEST['comp'])):
        comp = request.REQUEST['comp']
        service_t = loader.get_template(comp_dict[comp])
        if (request.REQUEST.has_key('day')):
          dic['WEEK_DAY'] = CONFIG.WEEK_DAY_NAME[int (request.REQUEST['day'])]
        else:
          dic['WEEK_DAY'] = CONFIG.WEEK_DAY_NAME[today.weekday()]
      else:
        service_t = loader.get_template('core/service.html')
        dic['ROOT'] = 'ROOT'
        dic['WEEK_DAY'] = CONFIG.WEEK_DAY_NAME[today.weekday()]
      dic['SERVICE'] = data
      dic['COMP'] = data.BuildComp()
      dic['GALLERY_INFO'] = gallery_info
      dic['PHOTO_INFO'] = photo_info
      dic['ROSTER_INFO'] = {}
      dic['LAYOUT_INFO'] = layout_info
      dic['TEMPLATE'] = layout.GetTemplate()
      dic['FORUM'] = forum_info.IsEnabled(name)
      dic['HIST'] = HistoryHelper.GetHistory(name,None,None,10) 
      dic['SESSION'] = request.session
      c = RequestContext(request,dic)
      return HttpResponse(service_t.render(c),mimetype = "text/html")
    except ServiceCore.DoesNotExist:
      return HttpResponse("Service Does Not Exist")

@browser_prefix
def Map(request):
  isIphone = (lambda x:'iPhone' in x or False)(request.META['HTTP_USER_AGENT'])
  isAndroid = (lambda x:'Android' in x or False)(request.META['HTTP_USER_AGENT'])
  if(isIphone):
    return redirect('/iphone_map')
  '''if(isAndroid):
    return redirect('/android_map')'''
  home_t = loader.get_template('core/map.html')
  hist = HistoryHelper.GetHistory(None,None,None,10)
  c = RequestContext(request,{'REQUEST':request.REQUEST,'CSS_ROOT':'default','HIST':hist,'SESSION':request.session})
  return HttpResponse(home_t.render(c))

#added by mike for setting iphone problem 20121008
@browser_prefix
def IphoneMap(request):
  home_t = loader.get_template('core/iphone_map.html')
  hist = HistoryHelper.GetHistory(None,None,None,10)
  c = RequestContext(request,{'REQUEST':request.REQUEST,'CSS_ROOT':'default','HIST':hist,'SESSION':request.session})
  return HttpResponse(home_t.render(c))


#added by mike for setting iphone problem 20121013
@browser_prefix
def MobileMap(request):
  home_t = loader.get_template('core/mobile_map.html')
  hist = HistoryHelper.GetHistory(None,None,None,10)
  c = RequestContext(request,{'REQUEST':request.REQUEST,'CSS_ROOT':'default','HIST':hist,'SESSION':request.session})
  return HttpResponse(home_t.render(c))

#added by mike for setting iphone problem 20121014
@browser_prefix
def AndroidMap(request):
  home_t = loader.get_template('core/android_map.html')
  hist = HistoryHelper.GetHistory(None,None,None,10)
  c = RequestContext(request,{'REQUEST':request.REQUEST,'CSS_ROOT':'default','HIST':hist,'SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def Search(request):
  isIphone = (lambda x:'iPhone' in x or False)(request.META['HTTP_USER_AGENT'])
  #isAndorid = (lambda x:'Android' in x or False)(request.META['HTTP_USER_AGENT'])
  if(isIphone):
    return redirect('/mobile/iphone')
  #if(isAndorid):
  #  return redirect('/andorid_map')
  home_t = loader.get_template('core/search.html')
  c = RequestContext(request,{'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def Main(request):
  main_t = loader.get_template('zoyoe.html')
  c = RequestContext(request,{'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(main_t.render(c))

@browser_prefix
def Searchlist(request):
  home_t = loader.get_template('core/list.html')
  c = Context({'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def Gamelist(request):
  home_t = loader.get_template('core/gamelist.html')
  c = Context({'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def Playgame(request):
  home_t = loader.get_template('core/game.html')
  c = Context({'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def Aboutus(request):
  home_t = loader.get_template('core/Aboutus.html')
  c = Context({'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def Manual(request):
  home_t = loader.get_template('core/manual.html')
  c = Context({'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def Warning(request):
  home_t = loader.get_template('core/warning.html')
  c = Context({'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))

@browser_prefix
def WarningHome(request):
  home_t = loader.get_template('core/warningHome.html')
  c = Context({'REQUEST':request.REQUEST,'CSS_ROOT':'default','SESSION':request.session})
  return HttpResponse(home_t.render(c))


